package com.base.gsyvideoplayer.tools;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.base.common.view.widget.imageView.GlideImageView;
import com.base.common.view.widget.imageView.ImageLoaderUtils;
import com.base.gsyvideoplayer.help.GSYVideoHelper;
import com.base.gsyvideoplayer.view.SampleVideo;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

public class GSYRecyclerVideoUtils {

    public final static String TAG = "GSYRecyclerVideoUtils";

    private int lastVisibleItem;

    private int firstVisibleItem;

    private GSYVideoHelper smallVideoHelper;

    private GSYVideoHelper.GSYVideoHelperBuilder gsySmallVideoHelperBuilder;
    private Activity activity;

    public void initView(Activity content, final RecyclerView recyclerView) {
        this.activity = content;
//        smallVideoHelper = new GSYVideoHelper(activity, new NormalGSYVideoPlayer(activity));
//        smallVideoHelper.setFullViewContainer(videoFullContainer);

        SampleVideo sampleVideo = new SampleVideo(activity);
        sampleVideo.setMoreScale(false);
        sampleVideo.setType(3);
        sampleVideo.setTitle(false);

        smallVideoHelper = new GSYVideoHelper(activity, sampleVideo);

        //配置
        gsySmallVideoHelperBuilder = new GSYVideoHelper.GSYVideoHelperBuilder();
        gsySmallVideoHelperBuilder
                .setHideActionBar(true)
                .setHideStatusBar(true)
                .setNeedLockFull(true)
                .setCacheWithPlay(true)
                .setAutoFullWithSize(true)
                .setShowFullAnimation(true)
                .setVideoTitle("")
                .setLockLand(true)
                .setVideoAllCallBack(new GSYSampleCallBack() {
                    @Override
                    public void onAutoComplete(String url, Object... objects) {
                        super.onAutoComplete(url, objects);
                        if (objects.length == 2 && objects[1] instanceof SampleVideo) {

                            SampleVideo video = (SampleVideo) objects[1];

                            video.setTitle(false);
                        }


                    }

                    @Override
                    public void onPrepared(String url, Object... objects) {
                        super.onPrepared(url, objects);
                        Debuger.printfLog("Duration " + smallVideoHelper.getGsyVideoPlayer().getDuration() + " CurrentPosition " + smallVideoHelper.getGsyVideoPlayer().getCurrentPositionWhenPlaying());
                    }

                    @Override
                    public void onQuitSmallWidget(String url, Object... objects) {
                        super.onQuitSmallWidget(url, objects);
                        //大于0说明有播放,//对应的播放列表TAG
                        if (smallVideoHelper.getPlayPosition() >= 0 && smallVideoHelper.getPlayTAG().equals(TAG)) {
                            //当前播放的位置
                            int position = smallVideoHelper.getPlayPosition();
                            //不可视的是时候
                            if ((position < firstVisibleItem || position > lastVisibleItem)) {
                                //释放掉视频
                                smallVideoHelper.releaseVideoPlayer();
                                if (recyclerView.getAdapter() != null) {
                                    recyclerView.getAdapter().notifyDataSetChanged();
                                }

                            }
                        }

                    }
                });

        smallVideoHelper.setGsyVideoOptionBuilder(gsySmallVideoHelperBuilder);

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            //添加滑动监听
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
                    lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                    Debuger.printfLog("firstVisibleItem " + firstVisibleItem + " lastVisibleItem " + lastVisibleItem);
                    //大于0说明有播放,//对应的播放列表TAG
                    if (smallVideoHelper.getPlayPosition() >= 0 && smallVideoHelper.getPlayTAG().equals(TAG)) {
                        //当前播放的位置
                        int position = smallVideoHelper.getPlayPosition();
                        //不可视的是时候
                        if ((position < firstVisibleItem || position > lastVisibleItem)) {
                            //如果是小窗口就不需要处理
                            if (!smallVideoHelper.isSmall() && !smallVideoHelper.isFull()) {
                                //小窗口
                                int size = CommonUtil.dip2px(activity, 150);
                                //actionbar为true才不会掉下面去
                                smallVideoHelper.showSmallVideo(new Point(size, size), true, true);
                            }
                        } else {
                            if (smallVideoHelper.isSmall()) {
                                smallVideoHelper.smallVideoToNormal();
                            }
                        }
                    }
                }
            });

        }

    }


    /**
     * @param position
     * @param imageView         player的封面
     * @param listItemContainer player的容器
     * @param listItemBtn       播放按键
     */
    public void addVideoPlayer(final int position, ImageView imageView, ViewGroup listItemContainer, View listItemBtn) {
        smallVideoHelper.addVideoPlayer(position, imageView, TAG, listItemContainer, listItemBtn);
    }





    /**
     * 重置视频
     */
    public void resetVideoPlayer() {
//        JavaMethod.setFieldValue(smallVideoHelper, "mPlayPosition", -1);
        smallVideoHelper.resetVideoPlayer();
    }

    public int getPlayPosition() {
        return smallVideoHelper.getPlayPosition();
    }

    /**
     * 开始播放
     *
     * @param position 播放器所处的位置
     * @param url      播放的url
     */
    public void startPlay(int position, String url) {
        smallVideoHelper.setPlayPositionAndTag(position, TAG);
        gsySmallVideoHelperBuilder.setVideoTitle(" ").setUrl(url);
        smallVideoHelper.startPlay();
    }


    public StandardGSYVideoPlayer getSampleVideo() {
        return smallVideoHelper.getGsyVideoPlayer();
    }

    /**
     * //获取封面
     *
     * @param url 视频的地址
     * @return
     */
    public GlideImageView getImageView(String url, final VideoOrientationInterface videoOrientationInterface) {
        final GlideImageView imageView = new GlideImageView(activity);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        if (videoOrientationInterface == null) {
            ImageLoaderUtils.loadImage(imageView, url, false);
        } else {
            Glide.with(activity)
                    .asBitmap()
                    .load(url).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    float w = resource.getWidth();
                    float h = resource.getHeight();
                    videoOrientationInterface.onSuccess(w, h);

                    imageView.setImageBitmap(resource);
                }
            });
        }


        return imageView;
    }


    public boolean onBackPressed() {
        if (smallVideoHelper != null && smallVideoHelper.backFromFull()) {
            return true;
        }
        return false;
    }


    public void onDestroy() {
        if (smallVideoHelper != null) {
            smallVideoHelper.releaseVideoPlayer();
            GSYVideoManager.releaseAllVideos();
        }
    }

    public interface VideoOrientationInterface {
        void onSuccess(float w, float h);
    }

}
